package com.qfedu.openplateform.warehouse.controller;

import com.qfedu.openplateform.common.entity.ResponseData;
import com.qfedu.openplateform.common.entity.WarehouseProduct;
import com.qfedu.openplateform.warehouse.lock.RedisLock;
import com.qfedu.openplateform.warehouse.service.WareService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/ware")
public class WareController {
    @Autowired
    private WareService wareService;
    @Autowired
    private RedisLock redisLock;
    @Autowired
    private StringRedisTemplate redisTemplate;


    @RequestMapping("/table")
    public ResponseData table() {
        ResponseData<List<WarehouseProduct>> responseData = new ResponseData<>();
        List<WarehouseProduct> productList = wareService.checkAllWare();
        responseData.setData(productList);
        responseData.setCode("0");
        return responseData;
    }

    @RequestMapping("/reduceStack")
    public ResponseData reduceStack(int pid) {
        ResponseData<Object> responseData = new ResponseData<>();
        WarehouseProduct ware = wareService.findWareById(pid);
        /*
        * 分布式锁
        * */
        if (redisLock.lock("key","SYNC",2)) {
            // 1.获取当前的库存,并判断数量
            Integer currentStack = ware.getCurrentCnt();
            if (currentStack <=0 ){ // 没有库存
                responseData.setMessage("抱歉，已售罄");
                return  responseData;
            }
            // 2.削减库存
            ware.setCurrentCnt(currentStack - 1);
            wareService.reduceWareStack(ware);
            // 释放锁
            redisLock.unlock("key");
            responseData.setMessage("库存扣减成功！");
            return responseData;
        } else {
            responseData.setMessage("库存扣减失败!!!");
            return responseData;
        }
    }
}
